//
//  RCUserAccountViewModel.swift
//  RCWeibo
//
//  Created by CL on 15/12/17.
//  Copyright © 2015年 CL. All rights reserved.
//

import UIKit
import AFNetworking
//在这里封装网络请求和业务逻辑
class RCUserAccountViewModel: NSObject {
    
    var userAccount: RCUserAccount?
    
    //重写构造方法，从沙盒中取用户数据
    override init() {
        
        userAccount = RCUserAccount.loadFromSandbox()
        super.init()
        
    }
    /// 计算属性， 用户是否登录
    var isLogin: Bool{
        return userAccount?.access_token != nil
    }
    /// 用户名
    var userName: String?{
    
        return userAccount?.name
    }
    /// 用户头像链接
    var userHeadIconUrl: NSURL?{
    
        return NSURL(string: userAccount?.avatar_large ?? "")
    }
    /// 用户token
    var userToken: String?{
    
        return userAccount?.access_token
    
    }
    
    //MARK:
    //MARK: 加载用户token
    func laodAccessToken(code: String, finished:(isSuccess: Bool) -> ()){
        
        let urlStr = "https://api.weibo.com/oauth2/access_token"
        //参数
        let params = ["client_id": client_id, "client_secret" : client_secret,"grant_type":"authorization_code","code":code, "redirect_uri":redirect_uri]
        
        AFN.POST(urlStr, parameters: params, progress: { (progress) -> Void in
            
            }, success: { (_, result) -> Void in
                print("成功")
                if let dict = result as? [String : AnyObject]{
                    
                    let userAccount = RCUserAccount(dict: dict)
                    
                    //通过token获取用户信息
                    self.loadUserInfo(userAccount, finished: finished)
                    
                 
                    
                }
                
            }) { (_, error) -> Void in
                print("失败")
                print(error)
                   finished(isSuccess: false)
        }
        
    }
    

    
    
    func loadUserInfo(userAccount: RCUserAccount, finished: (isSuccess: Bool) -> ()){
        
        
        let urlStr = "https://api.weibo.com/2/users/show.json"
        
        if let token = userAccount.access_token, uid = userAccount.uid{
            
            
            
            let params = ["access_token": token, "uid": uid]
            
            //        let AFN = AFHTTPSessionManager()
            AFN.GET(urlStr, parameters: params, progress: { (progress) -> Void in
                
                }, success: { (_, result) -> Void in
                    
                    
                    if let dict = result {
                        //拉指定用户数据
                        
                        let avatar_large = dict["avatar_large"] as! String
                        let name = dict["name"] as! String
                        
                        //存放到模型中去
                        userAccount.name = name
                        userAccount.avatar_large = avatar_large
                        
                        //获取完整用户信息
                        //存储用户信息
                        userAccount.saveToSandbox()
                        
                        //执行成功回调
                        finished(isSuccess: true)
                    }
                    
                }) { (_, error) -> Void in
                    
                    print(error)
                    
                    finished(isSuccess: false)
            }
            
        }
        
        
        
    }

    
    
    lazy var AFN: AFHTTPSessionManager = {
        
        let AFNM = AFHTTPSessionManager()
        AFNM.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        
        return AFNM
    }()


}
